/**
 * Created by Ysssssss on 19/4/21.
 */


import axios from 'axios'
import notify from "@utils/tip";
import { getCookie, clearCookie } from "@utils/cookie";
import paramsSnakeCase from "@utils/paramsSnakeCase";
import {getBilinInfo} from "@utils/localStorage";
import paramsDeleteEmpty from "@utils/paramsDeleteEmpty";
const devMode = process.env.NODE_ENV !== 'production';

export const editHeaderGToken = (value) => {
    axios.defaults.headers['G-Token'] = value
}
export const editHeaderBToken = (value) => {
    axios.defaults.headers['B-Token'] = value
}

// 环境的切换
axios.defaults.baseURL = process.env.FASTFOOD_URL

axios.defaults.timeout = 30000

axios.defaults.headers = {
    ...axios.defaults.headers,
    'G-Token': getCookie('bilin-user') || '',
    'B-Token': getCookie('bilin-brand') || '',
    'Content-Type':'application/json',
}

const reformedParams = config => {
    switch (config.method.toUpperCase()) {
        case 'GET':
            config.params = paramsSnakeCase(paramsDeleteEmpty({
                ...config.params,
            }))
            break;
        default:
            config.data = paramsSnakeCase(paramsDeleteEmpty({
                ...config.data,
            }))
    }
}

const setPStoreIdNormal = config => {
    switch (config.method.toUpperCase()) {
        case 'GET':
            config.params = paramsSnakeCase(paramsDeleteEmpty({
                ...config.params,
                pStoreId: config.params?.pStoreId === undefined ? (getBilinInfo('storeId') || 0) : config.params.pStoreId
            }))
            break;
        default:
            config.data = paramsSnakeCase(paramsDeleteEmpty({
                ...config.data,
                pStoreId: config.data?.pStoreId === undefined ? (getBilinInfo('storeId') || 0) : config.data.pStoreId
            }))
    }
}

const setPStoreIdAdmin = config => {
    switch (config.method.toUpperCase()) {
        case 'GET':
            config.params = paramsSnakeCase(paramsDeleteEmpty({
                ...config.params,
                pStoreId: config.params?.pStoreId === undefined ? (getBilinInfo('storeId') || 0) : config.params.pStoreId
            }))
            break;
        default:
            config.data = paramsSnakeCase(paramsDeleteEmpty({
                ...config.data,
            }))
            config.params = paramsSnakeCase({
                pStoreId: config.data?.pStoreId === undefined ? (getBilinInfo('storeId') || 0) : config.data.pStoreId
            })
    }
}

axios.interceptors.request.use(config => {
    window.loadingRefs && window.loadingRefs.show()
    switch(config.url.split('/')[1]) {
        case 'web':
            config.url = `${process.env.FASTFOOD_URL}${config.url}`
            config.headers = {
                ...config.headers,
                auth: getCookie('authInfo') || '',
                TOKEN: getCookie('employeeId') || '',
            }
            setPStoreIdNormal(config)
            break;
        case 'prod':
            config.url = `${process.env.BILIN_PRODUCT_CENTER_URL}${config.url}`
            setPStoreIdNormal(config)
            break;
        case 'shopping':
            config.url = `${process.env.SHOPPING_MALL_URL}${config.url}`
            config.headers = {
                ...config.headers,
                auth: getCookie('authInfo') || '',
                TOKEN: getCookie('employeeId') || '',
            }
            setPStoreIdNormal(config)
            break;
        case 'mall':
            config.url = `${process.env.BILIN_MALL_URL}${config.url}`
            setPStoreIdNormal(config)
            break;
        case 'inventory':
            config.url = `${process.env.BILIN_INVENTORY_URL}${config.url}`
            setPStoreIdNormal(config)
            break;
        case 'pay':
            config.url = `${process.env.BILIN_PAY_URL}${config.url}`
            setPStoreIdNormal(config)
            break;
        case 'market':
            config.url = `${process.env.BILIN_MARKET_URL}${config.url.replace('/market','')}`
            setPStoreIdNormal(config)
            break;
        case 'admin':
            config.url = `${process.env.BILIN_ADMIN_URL}${config.url}`
            setPStoreIdAdmin(config)
            break;
        case 'account':
            config.url = `${process.env.BILIN_ACCOUNT_URL}${config.url}`
            setPStoreIdAdmin(config)
            break;
        case 'open':
            config.url = `${process.env.BILIN_THIRDPARTY_URL}${config.url}`
            reformedParams(config)
            break;
        case 'of-open':
            config.url = `${process.env.OF_OPEN_URL}${config.url}`
            reformedParams(config)
            break;
        case 'member':
            config.url = `${process.env.BILIN_MEMBER_URL}${config.url}`
            reformedParams(config)
            break;
        default:
            break;
    }
    return config
}, error => {
    window.loadingRefs && window.loadingRefs.hide()
    return Promise.reject(error)
})

//响应拦截器即异常处理
axios.interceptors.response.use(({ data: response, config}) => {
    console.log('config', config)
    window.loadingRefs && window.loadingRefs.hide()
    if (response.success !== undefined && response.data !== undefined) {
        if (response.success) {
            return response.data
        } else {
            return Promise.reject({
                code: 200,
                error_message: response.msg,
                error_code: response.code,
            });
        }
    } else {
        if (response.type) {
            return response
        } else {
            if (response.error_code) {
                // if (response.error_code === 'INVALID_TOKEN') {
                //     notify(response.error_message)
                //     clearCookie('bilin-user')
                //     clearCookie('bilin-brand')
                //     setTimeout(() => {
                //         window.location.replace('/login')
                //     }, 2000)
                // } else {
                    return Promise.reject({
                        code: 200,
                        error_message: response.error_message,
                        error_code: response.error_code,
                    });
                // }
            }
            return response;
        }
    }
}, err => {
    window.loadingRefs && window.loadingRefs.hide()
    if (err && err.response) {
        if (err.response.data && err.response.data.code === '40003') {
            clearCookie('bilin-user')
            clearCookie('bilin-brand')
            setTimeout(() => {
                window.location.replace('/login')
            }, 1000)
        }
        if (err.response.data && (err.response.data.message || err.response.data.msg)) {
            err.response.error_message = err.response.data.message || err.response.data.msg
            err.response.reason = err.response.data.reason || ''
        } else {
            switch (err.response.status) {
                case 400:
                    err.response.error_message = '错误请求';
                    break;
                case 401:
                    err.response.error_message = '未授权，请重新登录';
                    break;
                case 403:
                    err.response.error_message = '拒绝访问';
                    break;
                case 404:
                    err.response.error_message = '请求错误,未找到该资源';
                    break;
                case 405:
                    err.response.error_message = '请求方法未允许';
                    break;
                case 408:
                    err.response.error_message = '请求超时';
                    break;
                case 500:
                    err.response.error_message = '服务器端出错';
                    break;
                case 501:
                    err.response.error_message = '网络未实现';
                    break;
                case 502:
                    err.response.error_message = '网络错误';
                    break;
                case 503:
                    err.response.error_message = '服务不可用';
                    break;
                case 504:
                    err.response.error_message = '网络超时';
                    break;
                case 505:
                    err.response.error_message = 'http版本不支持该请求';
                    break;
                default:
                    err.response.error_message = `连接错误${err.response.status}`;
            }
        }
    }
    return Promise.reject(err.response);
});

const sendingRepeatError = {
    code: 200,
    error_message: "请求中，请稍候……",
    error_code: "REPEAT_REQUEST"
}


const sendingPostRequest = {}

export function postAxios (url, data, handleError) {
    if (sendingPostRequest[url]) throw sendingRepeatError
    sendingPostRequest[url] = true
    return new Promise((resolve, reject) => {
        axios({
            method: 'POST',
            url,
            data
        }).then(res => {
            sendingPostRequest[url] = false
            resolve(res)
        }).catch(err => {
            sendingPostRequest[url] = false
            const errorMessage = err.error_message || '请求调用失败，请稍候重试'
            reject(err)
            handleError || notify(errorMessage)
        })
    })
}

const sendingPutRequest = {}

export function putAxios (url, data, handleError) {
    if (sendingPutRequest[url]) throw sendingRepeatError
    sendingPutRequest[url] = true
    return new Promise((resolve, reject) => {
        axios({
            method: 'PUT',
            url,
            data
        }).then(res => {
            sendingPutRequest[url] = false
            resolve(res)
        }).catch(err => {
            sendingPutRequest[url] = false
            const errorMessage = err.error_message || '请求调用失败，请稍候重试'
            reject(err)
            handleError || notify(errorMessage)
        })
    })
}

const sendingGetRequest = {}

export function getAxios (url, params, handleError) {
    if (sendingGetRequest[url]) throw sendingRepeatError
    sendingGetRequest[url] = true
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params
        }).then(res => {
            sendingGetRequest[url] = false
            resolve(res)
        }).catch(err => {
            sendingGetRequest[url] = false
            const errorMessage = err.error_message || '请求调用失败，请稍候重试'
            reject(err)
            handleError || notify(errorMessage)
        })
    })
}

const sendingDeleteRequest = {}
export function deleteAxios (url, data, handleError) {
    if (sendingDeleteRequest[url]) throw sendingRepeatError
    sendingDeleteRequest[url] = true
    return new Promise((resolve, reject) => {
        axios({
            method: 'DELETE',
            url,
            data,
        }).then(res => {
            sendingDeleteRequest[url] = false
            resolve(res)
        }).catch(err => {
            sendingDeleteRequest[url] = false
            const errorMessage = err.error_message || '请求调用失败，请稍候重试'
            reject(err)
            handleError || notify(errorMessage)
        })
    })
}
